from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def plot_color_histogram(image):
    # 将图像转换为NumPy数组
    image_np = np.array(image)

    # 检查图像的通道数
    if len(image_np.shape) == 2:
        # 灰度图像
        histogram = cv2.calcHist([image_np], [0], None, [256], [0, 256])
        plt.plot(histogram, color='k')
    elif len(image_np.shape) == 3:
        # 彩色图像，将图像从RGB转换为BGR（OpenCV使用BGR）
        image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)

        # 创建一个包含三个颜色通道的直方图
        colors = ('b', 'g', 'r')
        for i, color in enumerate(colors):
            histogram = cv2.calcHist([image_bgr], [i], None, [256], [0, 256])
            plt.plot(histogram, color=color)
    else:
        print("图像格式不支持")

    plt.title('Color Histogram')
    plt.xlabel('Bins')
    plt.ylabel('# of Pixels')
    plt.xlim([0, 256])
    plt.show()

def threshold_segmentation(image):
    # 将图像转换为NumPy数组
    image_np = np.array(image)

    # 转换为灰度图像
    if len(image_np.shape) == 3:
        image_gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
    else:
        image_gray = image_np

    # 应用Otsu's方法进行阈值分割
    threshold_value, binary_image = cv2.threshold(image_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    print(f"选取的阈值: {threshold_value}")
    return binary_image

def save_image(image_array, output_path):
    # 将NumPy数组转换为Pillow图像
    image = Image.fromarray(image_array)
    image.save(output_path)
    print(f"图像保存到: {output_path}")

# 示例调用
image_path = r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\data\real_data\level_3\1.tif'
output_path = r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\data\real_data\level_3\1_segmented.tif'
image = Image.open(image_path)

# 绘制颜色直方图
plot_color_histogram(image)

# 进行阈值分割
segmented_image = threshold_segmentation(image)

# 保存分割后的图像
save_image(segmented_image, output_path)

# 选取的阈值: 111.0
# 选取的阈值: 110.0
# 选取的阈值: 129.0